import os
import sys
import json
import time

# 添加更强大的错误处理
try:
    import win32print
    import win32api
    PYWIN32_INSTALLED = True
except ImportError:
    PYWIN32_INSTALLED = False
    print("警告: 未安装 pywin32 模块，部分功能将不可用", file=sys.stderr)

# 添加日志记录
def log_message(message, is_error=False):
    """记录日志消息到文件"""
    log_dir = os.path.join(os.path.dirname(__file__), 'logs')
    if not os.path.exists(log_dir):
        try:
            os.makedirs(log_dir)
        except Exception as e:
            print(f"创建日志目录失败: {str(e)}", file=sys.stderr)
            return
    
    log_file = os.path.join(log_dir, 'print_service.log')
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    log_type = 'ERROR' if is_error else 'INFO'
    
    try:
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(f"[{timestamp}] [{log_type}] {message}\n")
    except Exception as e:
        print(f"写入日志失败: {str(e)}", file=sys.stderr)

def resource_path(relative_path):
    """获取资源路径，支持开发和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.dirname(__file__)
    return os.path.join(base_path, relative_path)

def get_printers():
    """获取系统打印机列表"""
    if not PYWIN32_INSTALLED:
        error_msg = "未安装 pywin32 模块，无法获取打印机列表"
        log_message(error_msg, True)
        return {"success": False, "error": error_msg, "printers": []}
    
    printers = []
    try:
        default_printer = win32print.GetDefaultPrinter()
        
        # 尝试获取打印机列表
        try:
            printer_list = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS)
        except Exception as e:
            log_message(f"EnumPrinters 失败: {str(e)}", True)
            # 如果 EnumPrinters 失败，至少返回默认打印机
            return {
                "success": True,
                "printers": [{"name": default_printer, "isDefault": True}]
            }
        
        for printer in printer_list:
            printer_name = printer[2]
            printers.append({
                "name": printer_name,
                "isDefault": printer_name == default_printer
            })
        
        return {"success": True, "printers": printers}
    except Exception as e:
        error_msg = f"获取打印机列表失败: {str(e)}"
        print(error_msg, file=sys.stderr)
        log_message(error_msg, True)
        
        # 尝试使用备用方法获取打印机列表
        try:
            import subprocess
            result = subprocess.run(['wmic', 'printer', 'get', 'name'], capture_output=True, text=True)
            if result.returncode == 0:
                lines = result.stdout.strip().split('\n')[1:]  # 跳过标题行
                printers = [{"name": line.strip(), "isDefault": False} for line in lines if line.strip()]
                return {"success": True, "printers": printers}
        except Exception as backup_error:
            log_message(f"备用方法也失败: {str(backup_error)}", True)
        
        # 确保即使失败也返回空数组
        return {"success": False, "error": error_msg, "printers": []}

def print_file(file_path, printer_name, duplex=False, copies=1):
    """打印文件"""
    if not os.path.exists(file_path):
        return {"success": False, "error": f"文件不存在: {file_path}"}
    
    try:
        # 设置默认打印机
        original_printer = win32print.GetDefaultPrinter()
        win32print.SetDefaultPrinter(printer_name)
        
        # 使用 ShellExecute 打印
        for i in range(copies):
            win32api.ShellExecute(
                0,
                "print",
                file_path,
                None,
                ".",
                0
            )
            # 延时以防连续提交过快
            if i < copies - 1:
                time.sleep(1)
        
        # 恢复原始默认打印机
        win32print.SetDefaultPrinter(original_printer)
        
        return {
            "success": True, 
            "message": f"成功打印文件: {os.path.basename(file_path)}",
            "details": {
                "printer": printer_name,
                "copies": copies,
                "duplex": duplex
            }
        }
    
    except Exception as e:
        error_msg = str(e)
        print(f"打印失败: {error_msg}", file=sys.stderr)
        return {"success": False, "error": f"打印失败: {error_msg}"}

def batch_print(file_paths, printer_name, duplex=False, copies=1):
    """批量打印多个文件"""
    if not file_paths:
        return {"success": False, "error": "没有可打印的文件"}
    
    results = []
    success_count = 0
    
    for i, file_path in enumerate(file_paths):
        print(f"正在打印 {i+1}/{len(file_paths)}: {os.path.basename(file_path)}", file=sys.stderr)
        
        result = print_file(file_path, printer_name, duplex, copies)
        results.append({
            "file": os.path.basename(file_path),
            "success": result.get("success", False),
            "message": result.get("message", ""),
            "error": result.get("error", "")
        })
        
        if result.get("success", False):
            success_count += 1
    
    return {
        "success": success_count > 0,
        "message": f"打印完成: {success_count}/{len(file_paths)} 个文件成功",
        "details": {
            "total": len(file_paths),
            "success": success_count,
            "failed": len(file_paths) - success_count,
            "results": results
        }
    }

def test_printer(printer_name):
    """测试打印机是否可用"""
    try:
        # 创建一个临时文本文件
        test_file = os.path.join(os.environ.get('TEMP', '.'), 'printer_test.txt')
        with open(test_file, 'w', encoding='utf-8') as f:
            f.write("打印机测试页\n")
            f.write("=" * 30 + "\n")
            f.write(f"打印机: {printer_name}\n")
            f.write(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write("=" * 30 + "\n")
            f.write("如果您看到此页面，说明打印机工作正常。\n")
        
        # 打印测试页
        result = print_file(test_file, printer_name, False, 1)
        
        # 删除临时文件
        try:
            os.remove(test_file)
        except:
            pass
        
        return result
    except Exception as e:
        return {"success": False, "error": f"测试打印机失败: {str(e)}"}

def get_system_info():
    """获取系统信息"""
    import platform
    try:
        default_printer = win32print.GetDefaultPrinter()
    except:
        default_printer = "未知"
        
    return {
        "success": True,
        "os": platform.system(),
        "version": platform.version(),
        "architecture": platform.architecture()[0],
        "python_version": platform.python_version(),
        "default_printer": default_printer
    }

# 命令行入口点
if __name__ == "__main__":
    # 记录启动信息和参数
    log_message(f"脚本启动，参数: {sys.argv}")
    
    # 检查 Python 版本和依赖
    import platform
    log_message(f"Python 版本: {platform.python_version()}")
    log_message(f"pywin32 已安装: {PYWIN32_INSTALLED}")
    
    # 从命令行参数获取操作类型
    if len(sys.argv) < 2:
        error_msg = "缺少操作参数"
        log_message(error_msg, True)
        print(json.dumps({"success": False, "error": error_msg}))
        sys.exit(1)
    
    action = sys.argv[1]
    log_message(f"执行操作: {action}")
    
    try:
        if action == "get-printers":
            # 获取打印机列表
            result = get_printers()
            print(json.dumps(result))
            
        elif action == "print":
            # 打印文件
            if len(sys.argv) < 4:
                print(json.dumps({"success": False, "error": "缺少打印参数"}))
                sys.exit(1)
                
            file_path = sys.argv[2].strip('"')  # 移除可能的引号
            printer_name = sys.argv[3].strip('"')
            duplex = len(sys.argv) > 4 and sys.argv[4].lower() == "true"
            copies = int(sys.argv[5]) if len(sys.argv) > 5 else 1
            
            result = print_file(file_path, printer_name, duplex, copies)
            print(json.dumps(result))
        
        elif action == "batch-print":
            # 批量打印文件
            if len(sys.argv) < 4:
                print(json.dumps({"success": False, "error": "缺少打印参数"}))
                sys.exit(1)
                
            files_json = sys.argv[2].strip('"')  # 文件列表的JSON字符串
            printer_name = sys.argv[3].strip('"')
            duplex = len(sys.argv) > 4 and sys.argv[4].lower() == "true"
            copies = int(sys.argv[5]) if len(sys.argv) > 5 else 1
            
            try:
                file_paths = json.loads(files_json)
                result = batch_print(file_paths, printer_name, duplex, copies)
                print(json.dumps(result))
            except json.JSONDecodeError:
                print(json.dumps({"success": False, "error": "无效的文件列表格式"}))
        
        elif action == "test-printer":
            # 测试打印机
            if len(sys.argv) < 3:
                print(json.dumps({"success": False, "error": "缺少打印机名称"}))
                sys.exit(1)
                
            printer_name = sys.argv[2].strip('"')
            result = test_printer(printer_name)
            print(json.dumps(result))
        
        elif action == "system-info":
            # 获取系统信息
            result = get_system_info()
            print(json.dumps(result))
            
        else:
            print(json.dumps({"success": False, "error": f"未知操作: {action}"}))
            sys.exit(1)
    except Exception as e:
        error_msg = f"执行失败: {str(e)}"
        log_message(error_msg, True)
        print(json.dumps({"success": False, "error": error_msg}))
        sys.exit(1)